package cn.itsource.product.controller;

import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.PageList;
import cn.itsource.product.domain.Product;
import cn.itsource.product.query.ProductQuery;
import cn.itsource.product.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/product")
//@CrossOrigin
public class ProductController {

    @Autowired
    private IProductService productService;
    //查询所有  @GetMapping
    @GetMapping//http://127.0.0.1:8080/dept/
    public List<Product> queryAll(){
        return productService.queryAll();
    }

    // 新增和修改使用：@PutMapping  通过有没有Id来确定是不是修改
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Product product){
        System.out.println(product);
        System.out.println(product.getDetail());

        try {
            if (product.getId() != null) {
                //
                productService.update(product);
            }else{
                productService.add(product);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me()
                    .setMessage("操作失败！"+e.getMessage());
        }
    }

    //删除数据    @DeleteMapping("/{id}")
    // 127.0.0.1/dept/9
    @DeleteMapping("/{id}")
    public AjaxResult deleteById(@PathVariable("id") Long id){
        /*链式编程思维*/
        try {
            productService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me()
                    .setMessage("操作失败！"+e.getMessage());
        }
    }

    /**
     * 在restFull风格接口中，使用{}占位
     * 那么在取值的时候，使用@PathVariable来获取占位的值
     * @param id
     * @return
     */
    @GetMapping("/{id}")//http://127.0.0.1:8080/dept/1
    public Product queryById(@PathVariable("id") Long id){
        return productService.queryById(id);
    }

    //分页查询
    @PostMapping
    public PageList<Product> queryPage(@RequestBody ProductQuery query){
        return productService.queryPage(query);
    }
    //分页 前端普通用户
    @PostMapping("/list")
    public PageList<Product> queryPageList(@RequestBody ProductQuery query){
        query.setState(1);
        return productService.queryPage(query);
    }

    @PatchMapping("/onSale")
    public AjaxResult onSale(@RequestBody Long[] ids){
        /*链式编程思维*/
        try {
            productService.onSale(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me()
                    .setMessage("操作失败！"+e.getMessage());
        }
    }
   
}
